package com.yx.yinshanjinniu.application;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.yx.yinshanjinniu.bean.LatestProPriceBean;
import com.yx.yinshanjinniu.eventbus.EventCenter;
import com.yx.yinshanjinniu.eventbus.EventConstants;
import com.yx.yinshanjinniu.utils.LogUtil;
import com.zc.mychart.model.GoodsAllBean;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * WebSocket数据处理管理器
 * 负责处理来自WebSocket的数据，并高效地更新数据模型和UI
 */
public class WebSocketDataManager {
    private static final String TAG = "WebSocketDataManager";

    // 单例实现
    private static volatile WebSocketDataManager instance;

    // 数据存储
    private Map<String, GoodsAllBean> allGoodMap;
    private List<GoodsAllBean> allGoodsList;

    // 线程池
    private ExecutorService executor;

    // 记录已更新的产品代码，用于差量更新
    private final Set<String> updatedProductCodes = new HashSet<>();

    // 主线程Handler，用于UI更新
    private Handler mHandler;

    // 定时UI刷新任务
    private Runnable mRefreshMarketUITask;
    private Runnable mRefreshFollowUITask;

    // 单例Gson，避免频繁创建
    private static final Gson gson = new Gson();

    // 私有构造函数
    private WebSocketDataManager() {
        // 初始化线程池
        executor = Executors.newCachedThreadPool();

        // 创建主线程Handler
        mHandler = new Handler(Looper.getMainLooper());

        // 初始化UI刷新任务
        initRefreshTasks();
    }

    /**
     * 获取单例实例
     */
    public static WebSocketDataManager getInstance() {
        if (instance == null) {
            synchronized (WebSocketDataManager.class) {
                if (instance == null) {
                    instance = new WebSocketDataManager();
                }
            }
        }
        return instance;
    }

    /**
     * 设置数据源引用
     */
    public void setDataSource(Map<String, GoodsAllBean> goodsMap, List<GoodsAllBean> goodsList) {
        this.allGoodMap = goodsMap;
        this.allGoodsList = goodsList;
    }

    /**
     * 启动刷新任务
     */
    public void startRefreshTasks() {
        mHandler.post(mRefreshMarketUITask);
        mHandler.post(mRefreshFollowUITask);
    }

    /**
     * 停止刷新任务
     */
    public void stopRefreshTasks() {
        mHandler.removeCallbacks(mRefreshMarketUITask);
        mHandler.removeCallbacks(mRefreshFollowUITask);
    }

    /**
     * 初始化UI刷新任务
     */
    private void initRefreshTasks() {
        // 行情更新任务 - 高频率1秒
        mRefreshMarketUITask = new Runnable() {
            @Override
            public void run() {
                // 差量更新 - 只通知有变化的产品
                synchronized (updatedProductCodes) {
                    if (!updatedProductCodes.isEmpty()) {
                        EventBus.getDefault().post(new EventCenter<Set<String>>(
                                EventConstants.EVENTCODE_UPDATE_PRO_PRICE,
                                new HashSet<>(updatedProductCodes)));
                        updatedProductCodes.clear();
                    }
                }
                // 设置下一次刷新的时间点
                mHandler.postDelayed(this, 1000);
            }
        };

        // 跟单更新任务 - 低频率5秒
        mRefreshFollowUITask = new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new EventCenter(EventConstants.EVENTCODE_UPDATE_PRO_FOLLOW_PRICE));
                mHandler.postDelayed(this, 5000);
            }
        };
    }

    /**
     * 处理WebSocket数据
     */
    public void processWebSocketData(String webSocketJson) {
        if (TextUtils.isEmpty(webSocketJson)) {
            return;
        }

        try {
            // 提交到线程池处理，异步执行
            executor.submit(() -> parseAndUpdateData(webSocketJson));
        } catch (Exception e) {
            LogUtil.e(TAG, "处理WebSocket数据异常" + e);
        }
    }

    /**
     * 解析并更新数据
     */
    private void parseAndUpdateData(String webSocketJson) {
        try {
            // 解析数据
            LatestProPriceBean priceBean = gson.fromJson(webSocketJson, LatestProPriceBean.class);
            if (priceBean == null || TextUtils.isEmpty(priceBean.content)) {
                return;
            }

            // 分割内容
            String[] contentArray = priceBean.content.split("\\|");
            if (contentArray.length < 1) {
                return;
            }

            // 获取产品代码
            String productCode = contentArray[0];

            // 查找对应的产品
            GoodsAllBean goodsAllBean = allGoodMap.get(productCode);
            if (goodsAllBean == null) {
                return;
            }

            // 根据消息类型处理数据
            boolean isUpdated = false;

            if ("state".equals(priceBean.type)) {
                // 处理状态更新
                if (contentArray.length > 1) {
                    int newDuringType = Integer.parseInt(contentArray[1]);
                    if (goodsAllBean.during_type != newDuringType) {
                        // 状态有变化才更新
                        updateProductState(productCode, newDuringType);
                        isUpdated = true;
                    }
                }
            } else if ("quote".equals(priceBean.type) && contentArray.length > 6) {
                // 处理价格更新
                double newLatestPrice = Double.parseDouble(contentArray[3]);
                double newBeginningPrice = Double.parseDouble(contentArray[4]);
                double newEndLastDayPrice = Double.parseDouble(contentArray[2]);
                double newHighPrice = Double.parseDouble(contentArray[5]);
                double newLowwestPrice = Double.parseDouble(contentArray[6]);

                // 判断价格是否有变化
                if (goodsAllBean.latest_price != newLatestPrice ||
                    goodsAllBean.price_beginning != newBeginningPrice ||
                    goodsAllBean.price_end_lastday != newEndLastDayPrice ||
                    goodsAllBean.high_price != newHighPrice ||
                    goodsAllBean.lowwest_price != newLowwestPrice) {

                    // 更新价格数据
                    updateProductPrice(productCode, contentArray[1],
                            newEndLastDayPrice, newLatestPrice, newBeginningPrice,
                            newHighPrice, newLowwestPrice);
                    isUpdated = true;
                }
            }

            // 如果有更新，添加到更新列表
            if (isUpdated) {
                synchronized (updatedProductCodes) {
                    updatedProductCodes.add(productCode);
                }
            }
        } catch (Exception e) {
            LogUtil.e(TAG, "解析或更新数据异常" + e);
        }
    }

    /**
     * 更新产品状态
     */
    private void updateProductState(String productCode, int duringType) {
        // 更新 map 中的状态
        GoodsAllBean goodsAllBean = allGoodMap.get(productCode);
        if (goodsAllBean != null) {
            goodsAllBean.during_type = duringType;
        }

        // 更新列表中的状态
        for (GoodsAllBean item : allGoodsList) {
            if (item.pro_code.equals(productCode)) {
                item.during_type = duringType;
                break;
            }
        }
    }

    /**
     * 更新产品价格
     */
    private void updateProductPrice(String productCode, String updateTime,
                                   double endLastDayPrice, double latestPrice,
                                   double beginningPrice, double highPrice, double lowwestPrice) {
        // 更新 map 中的价格
        GoodsAllBean goodsAllBean = allGoodMap.get(productCode);
        if (goodsAllBean != null) {
            goodsAllBean.update_time = updateTime;
            goodsAllBean.latest_price = latestPrice;
            goodsAllBean.price_end_lastday = endLastDayPrice;
            goodsAllBean.price_beginning = beginningPrice;
            goodsAllBean.high_price = highPrice;
            goodsAllBean.lowwest_price = lowwestPrice;
        }

        // 更新列表中的价格
        for (GoodsAllBean item : allGoodsList) {
            if (item.pro_code.equals(productCode)) {
                item.update_time = updateTime;
                item.latest_price = latestPrice;
                item.price_end_lastday = endLastDayPrice;
                item.price_beginning = beginningPrice;
                item.high_price = highPrice;
                item.lowwest_price = lowwestPrice;
                break;
            }
        }
    }

    /**
     * 释放资源
     */
    public void destroy() {
        // 停止所有任务
        stopRefreshTasks();

        // 关闭线程池
        if (executor != null && !executor.isShutdown()) {
            executor.shutdown();
        }

        // 清空数据
        if (updatedProductCodes != null) {
            updatedProductCodes.clear();
        }

        // 释放单例
        instance = null;
    }
}
